<template>
  <div class="bg-fa">
    <audio id="audio" preload="auto" @error="playAudioError" @ended="playAudioEnd" class="c-pf c-p-l-100"></audio>
    <div class="" :class="[item.isActive ? 'c-bg-white' : '', index == examinationList.length - 1 ? '' : 'c-bd-b1-mgray']" @click="changeItem(index)" :id='"examItem" + index' v-for="(item, index) in examinationList" :key="index">
      <div :class="item.isActive ? 'top-bx c-mb64' : 'c-mb24'" class="c-flex-row c-aligni-center c-justify-sb c-ph32 c-pv20">
        <div class="c-w33 c-fs24 c-fc-white c-mr40">
        </div>
        <div class="c-w33 c-fs26 c-fc-sblack c-textAlign-c">{{item.type == 1 ? '单选题' : (item.type == 2 ? '多选题': '朗读题')}}</div>
        <div class="c-w33 c-fs24 c-fc-sblack c-ml26 c-textAlign-r">{{index + 1}}<span class="c-fc-gray">/{{examinationList.length}}</span></div>
      </div>

      <div class="c-ph64" :class="item.isActive ? '' : 'c-pb40'" v-if="item.problemShowType == 3">
        <div class="c-ph48 c-br10" v-show="item.isActive">
          <img class="c-w100 c-br10" v-if="item.avatar[0].avatar" :src="$addXossFilter(item.avatar[0].avatar, require('../../../assets/default3_5.png'))" alt="">
        </div>
        <div class="c-fs30 c-fw-b c-lh48 c-fc-sblack" :class="[isReject == 1 ? 'colorB' : '', item.isActive ? 'c-mt32' : '']" v-if="item.problem && (!wordAnly || isReject == 1)">{{item.problem}}</div>
        <div class="c-fs30 c-fw-b c-lh48 c-mt32" v-html="wordAnly" v-if="item.problem && wordAnly && isReject == 0"></div>
        <div class="c-fs24 c-fc-gray c-mt8" v-if="item.translate && item.type == 6">{{item.translate ? item.translate : ''}}</div>
      </div>

      <div v-show="item.isActive" class="c-flex-row c-aligni-center c-justify-sb c-ph64 c-mt100">
        <div class="c-ww80 c-hh80">
          <img @click="replay" v-if="!showLoudspeaker" class="c-ww80 c-hh80 c-brp50" :src="require('../../../assets/i/wap/exam/play.png')" alt="">
          <img v-if="showLoudspeaker" class="c-ww80 c-hh80 c-brp50" :src="require('../../../assets/i/wap/exam/loudspeaker.gif')" alt="">
        </div>
        <div @click="clickRecordBtn(item.problem)" :class="recordStatus == 'RECORDING' ? 'record_out' : ''" class="record-circle c-flex-row c-flex-center">
          <span v-if="recordStatus == 'RECORDING'" class="c-fs40 c-fc-white icon iconfont">&#xe8ae;</span>
          <span v-else class="c-fs40 c-fc-white icon iconfont">&#xe81f;</span>
        </div>
        <div :class="score === '' ? 'option-bg' : (Number(score) >= 85 ? 'stripe-right' : (Number(score) >= 60 ? 'test-bg c-fc-white' : 'stripe-wrong'))" class="c-ww80 c-hh80 c-brp50 c-flex-row c-flex-center c-fs36">{{score === '' ? '' : Number(score).toFixed(0)}}</div>
      </div>
      <div v-show="item.isActive" class="c-fs20 c-fc-gray c-textAlign-c c-mt28 c-pb80">点击话筒，{{recordStatus == "RECORDING" ? "结束" : "开始"}}录音<span v-if="recordStatus == 'RECORDING'">(剩余{{60-recordTime}}秒)</span></div>

      <div v-show="!item.isActive && (item.problemShowType != 3)" class="c-flex-row c-aligni-center c-justify-sb c-ph64 c-mt24 c-pb40">
        <div class="c-ww80 c-hh80">
          <img class="c-ww80 c-hh80 c-brp50" :src="require('../../../assets/i/wap/exam/play.png')" alt="">
        </div>
        <div class="record-circle c-flex-row c-flex-center">
          <span class="c-fs40 c-fc-white icon iconfont">&#xe81f;</span>
        </div>
        <div class="c-ww80 c-hh80 c-brp50 c-flex-row c-flex-center c-fs36 option-bg"></div>
      </div>
    </div>
    <div class="btn-wrap c-flex-row c-flex-center">
      <div @click="goResult" v-if="hasStart == 2" class="c-fs28 tr-fc c-ww240 c-hh72 c-br36 tr-bd c-flex-row c-flex-center c-mr40">上一次测试结果</div>
      <div @click="goTest" :class="enableResurvey != 1 ? 'tr-cd' : (isResurvey ? 'tr-bg' : 'tr-cd')" class="c-fs28 c-fc-white c-ww240 c-hh72 c-br36 c-flex-row c-flex-center">{{enableResurvey != 1 ? '不可重测' : (isResurvey ? '立即测试' : (showTime+'后重测'))}}</div>
    </div>
  </div>
</template>

<script>
// import OpenModal from "@/components/templates/common/openModal.vue";
import { utilJs, wxUtilJs } from "@/utils/common.js"
import record from "@/utils/recorder.js";
import transWorker from '@/utils/transcode.worker.js'
import { Base64 } from '@/utils/base64js.js'
import parser from 'fast-xml-parser'
// import defultImg from '@/assets/defult270.png'
let recordTimeCon; //录音计时控制器
let currentLocalId; //当前录音ID
// let recorder = null;
// let isLoading = false;
// let mp3Url = '';
let heightArr = [];
let timeCountDown = null;
let timeCounts = 0;
// let transWorker = new TransWorker()
export default {
  name: "SpeechStudy",
  components: {
    // OpenModal
  },
  props: [],
  data() {
    return {
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : 'mb5_default',
      paperMainId: -1,
      examinationInfo: null,
      opList: [],
      showPause: false, //暂停弹窗
      problemShowType: -1, //题目类型  1:语音播放（不显示朗读内容）  2：显示内容（无语音） 3：语音播放+内容显示
      answerShowType: -1, //选项类型  1:语音播放（不显示朗读内容） 4: 只有文字，没有图片 5:有图片
      playAudioIndex: -1, //播放索引 -1：播放题目 0：播放第一个选项 1：播放第二个选项。。。
      playAudioSrc: '', //当前播放的地址
      userAnSwer: [],
      rightAnswer: '',
      isOver: 0,
      paperDetailId: -1,
      examId: -1,
      recordStatus: "START",
      recordTime: 0,
      speakType: -1, //1:中文 2：英文
      type: -1, //1：单选 2：多选 6：朗读
      score: '', //朗读题得分
      hasChoosed: 0, //是否已经选择答案 0：未选择 1：已选择
      hasRecord: 0, //是否已经录音 0：未录音 1：已录音
      isQuestionEnd: 0, //题目是否已经念完 0:未念完 1：已念完
      showLoudspeaker: false,
      examModel: 1, //1：考试模式 2：练习模式
      paperType: 4, //4: 语言试卷 5:朗读课程
      isStudy: 1, //1、考试模式 2 学习模式
      wordAnly: "",
      praticeTimes: 0,
      isReject: 0,
      showIllustration: true,
      playIndex: 0,
      examinationList: [],
      hasStart: 0,
      goOnNum: 1,
      isResurvey: true,
      showTime: '',
      enableResurvey: 1,
      isWeiXin: true,
      qiniuInfo: {}, //录音完后的音频上传到七牛，这里是七牛的相关信息
      blob: '', //录音之后要上传七牛的音频文件
      ttId: "",
      tpId: "",
      tlId: "",
      progress: "",
      audioData: [],
      recordFlag: false,
    };
  },
  created() {
    utilJs.appShare(this);
  },
  activated() {
    setDocumentTitle("学习");// eslint-disable-line
    this.paperMainId = this.$route.query.paperMainId;
    this.isStudy = this.$route.query.isStudy ? 2 : 1;
    this.hasStart = this.$route.query.hasStart;
    this.goOnNum = this.$route.query.goOnNum;
    this.showPause = false;
    this.examinationInfo = null;
    this.recordStatus = "START";
    this.opList = [];
    this.praticeTimes = 0;
    this.hasRecord = 0;
    this.examinationList = [];
    this.playIndex = 0;
    this.isResurvey = true;
    this.showTime = '';
    this.enableResurvey = 1;
    heightArr = [];
    this.ttId = this.$route.query.ttId || "";
    this.tpId = this.$route.query.tpId || ""; //环节id
    this.tlId = this.$route.query.tlId || "";
    this.progress = this.$route.query.progress || "";
    this.getList();
    this.recordCheck()
    this.isWeiXin = utilJs.isWeiXin();
    if (!utilJs.isWeiXin() || this.recordFlag) {
      utilJs.getMethod(global.apiurl + "common/qiniu/uploadToken", res => {
        this.qiniuInfo.qiNiuToken = res;
      });
    }
    this.wechatShare();
  },
  deactivated() {
    if (!this.isWeiXin && record != null) {
      record.recClose();
    }
  },
  mounted() { },
  methods: {
    goResult() {
      this.$routerGo(this, "push", {
        path: "/homePage/voiceTest/voiceTestResult",
        query: { paperMainId: this.paperMainId, ttId: this.ttId, tpId: this.tpId, tlId: this.tlId, progress: this.progress }
      });
    },
    goTest() {
      if (this.enableResurvey != 1 || this.isResurvey == false) {
        return
      }
      if (this.hasStart == 0 || this.hasStart == 2) {
        this.$routerGo(this, "replace", {
          path: "/homePage/voiceTest/voiceTestAnswer",
          query: { paperMainId: this.paperMainId, topicId: 0, goOnNum: 1, ttId: this.ttId, tpId: this.tpId, tlId: this.tlId, progress: this.progress }
        });
      } else if (this.hasStart == 1) {
        this.$routerGo(this, "replace", {
          path: "/homePage/voiceTest/voiceTestAnswer",
          query: { paperMainId: this.paperMainId, topicId: 0, goOnNum: this.goOnNum, ttId: this.ttId, tpId: this.tpId, tlId: this.tlId, progress: this.progress }
        });
      }
    },
    getList() {
      let $this = this;

      utilJs.getMethod(global.apiurl + 'speech/practiceList/' + this.paperMainId, function (res) {
        let intervalTime = res.baseSet.intervalTime;
        let nt = (new Date()).getTime();
        let lt = res.baseSet.handAt ? utilJs.getTimeByDate(res.baseSet.handAt) : '';
        $this.examinationList = res.questions;
        $this.enableResurvey = res.baseSet.enableResurvey;
        if ($this.enableResurvey == 1) {
          if ((Number(intervalTime) != 0) && (lt != '') && (lt + intervalTime * 60 * 60 * 1000 > nt)) {
            $this.isResurvey = false;
            timeCounts = lt + (intervalTime * 60 * 60 * 1000) - nt;
            timeCountDown = setInterval(function () {
              timeCounts -= 1000;
              let secondTime = parseInt(timeCounts / 1000);
              let minuteTime = 0;
              let hourTime = 0;
              if (secondTime > 60) {
                minuteTime = parseInt(secondTime / 60);
                secondTime = parseInt(secondTime % 60);
                if (minuteTime > 60) {
                  hourTime = parseInt(minuteTime / 60);
                  minuteTime = parseInt(minuteTime % 60);
                }
              }
              $this.showTime = minuteTime > 0 ? (hourTime > 0 ? ((hourTime > 10 ? hourTime : '0' + hourTime) + ':' + (minuteTime > 10 ? minuteTime : '0' + minuteTime) + ':' + (secondTime > 10 ? secondTime : '0' + secondTime)) : ((minuteTime > 10 ? minuteTime : '0' + minuteTime) + ':' + (secondTime > 10 ? secondTime : '0' + secondTime))) : (secondTime + 's');
              if (timeCounts <= 1000) {
                $this.showTime = '';
                $this.isResurvey = true;
                clearInterval(timeCountDown)
              }
            }, 1000)
          } else {
            $this.isResurvey = true;
          }
        }
        for (let i = 0; i < $this.examinationList.length; i++) {
          $this.examinationList[i].isActive = false;
        }
        $this.examinationList[0].isActive = true;
        $this.$nextTick(() => {
          for (let i = 0; i < $this.examinationList.length; i++) {
            heightArr[i] = document.getElementById('examItem' + i).offsetHeight;
          }
          // setTimeout(function () {
          //   $this.toPlay();
          // }, 1000)
        });
      })
    },
    toPlay() {
      if (this.recordStatus == "RECORDING") {
        wxUtilJs.stopRecord();
        clearInterval(recordTimeCon);
        this.recordStatus = "START";
      }
      if (!document.getElementById('audio').ended) {
        document.getElementById("audio").pause();
      }
      this.showLoudspeaker = true;
      this.playRadio();
    },
    changeItem(aIndex) {
      if (aIndex == this.playIndex) {
        return;
      }
      this.hasRecord = 0;
      this.score = '';
      this.wordAnly = '';
      if (this.recordStatus == "RECORDING") {
        this.setStatus('START')
        clearInterval(recordTimeCon);
        return
      }
      if (!document.getElementById('audio').ended) {
        document.getElementById("audio").pause();
      }
      for (let i = 0; i < this.examinationList.length; i++) {
        this.examinationList[i].isActive = false;
      }
      this.examinationList[aIndex].isActive = true;
      this.playIndex = aIndex;
      this.$forceUpdate();
      this.$nextTick(() => {
        let scHeight = 0;
        // setTimeout(function () {
        for (let i = 0; i < this.examinationList.length; i++) {
          heightArr[i] = document.getElementById('examItem' + i).offsetHeight;
        }
        for (let j = 0; j < aIndex; j++) {
          scHeight = scHeight + heightArr[j];
        }
        // if (document.documentElement.scrollTop != null && document.documentElement.scrollTop != undefined) {
        document.documentElement.scrollTop = scHeight;
        // } else {
        document.body.scrollTop = scHeight;
        // }
        // }, 100)
      });
      this.toPlay();
    },
    goOnTest() {
      this.showPause = false;
      if (document.getElementById('audio').ended && this.answerShowType == 1 &&
      this.type != 6 && this.playAudioIndex < this.opList.length) {
        this.playAudioIndex++;
        this.playRadio();
      } else if (!document.getElementById('audio').ended) {
        document.getElementById("audio").play();
      }
    },
    clickExit() {
      //点击退出测试
      this.showPause = false;
      this.$router.go(-1);
    },
    restart() {
      this.showPause = false;
      utilJs.getMethod(global.apiurl + 'exam/transit/' + this.paperMainId + '?topicId=0', function (res) {
      })
    },
    testNow() {
      // this.examModel = 1;
      this.isStudy = 1;
      utilJs.getMethod(global.apiurl + 'exam/transit/' + this.paperMainId + '?topicId=0', function (res) {
        // $this.getQuestion();
      });
    },
    clickRecordBtn() {
      if (this.recordStatus != "RECORDING") {
        this.clickStartRecord();
      } else {
        this.clickStopRecord();
      }
    },
    // 暂停录音
    recorderStop(state) {
      if (state == 1) {
        this.$showCjToast({
          text: "webSocket连接失败",
          type: "warn",
          time: 1000
        });
      }
    // safari下suspend后再次resume录音内容将是空白，设置safari下不做suspend
      if (!(/Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgen))) {
        this.audioContext && this.audioContext.suspend()
      }
      this.setStatus('START')
    },
    //检测是否可以录音
    recordCheck() {
      // let $this = this
      this.audioData = []
      // $this.audioData.push(...transWorker.onmessage())
      navigator.getUserMedia =
      navigator.getUserMedia ||
      navigator.webkitGetUserMedia ||
      navigator.mozGetUserMedia ||
      navigator.msGetUserMedia

    // 创建音频环境
      try {
        this.audioContext = new (window.AudioContext || window.webkitAudioContext)()
        this.audioContext.resume()
        if (!this.audioContext) {
          this.recordFlag = false
          return
        }
      } catch (e) {
        if (!this.audioContext) {
          this.recordFlag = false
          return
        }
      }
      this.recordFlag = false
      this.audioContext && this.audioContext.close()
    },
    // 初始化浏览器录音
    recorderInit() {
      // let $this = this
      this.audioData = []
      // $this.audioData.push(...transWorker.onmessage())
      navigator.getUserMedia =
      navigator.getUserMedia ||
      navigator.webkitGetUserMedia ||
      navigator.mozGetUserMedia ||
      navigator.msGetUserMedia

    // 创建音频环境
      try {
        this.audioContext = new (window.AudioContext || window.webkitAudioContext)()
        this.audioContext.resume()
        if (!this.audioContext) {
          this.$showCjToast({
            text: "浏览器不支持webAudioApi相关接口",
            type: "warn",
            time: 1500
          });
          return
        }
      } catch (e) {
        if (!this.audioContext) {
          this.$showCjToast({
            text: "浏览器不支持webAudioApi相关接口",
            type: "warn",
            time: 1500
          });
          return
        }
      }

    // 获取浏览器录音权限
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices
        .getUserMedia({
          audio: {sampleRate:48000, autoGainControl:false},
          video: false,
        })
        .then(stream => {
          getMediaSuccess(stream)
        })
        .catch(e => {
          getMediaFail(e)
        })
      } else if (navigator.getUserMedia) {
        navigator.getUserMedia(
          {
            audio: true,
            video: false,
          },
        stream => {
          getMediaSuccess(stream)
        },
        function (e) {
          getMediaFail(e)
        }
      )
      } else {
        this.$showCjToast({
          text: "无法获取浏览器录音功能，请升级浏览器或使用chrome",
          type: "warn",
          time: 1500
        });
        this.audioContext && this.audioContext.close()
        return
      }
    // 获取浏览器录音权限成功的回调
      let getMediaSuccess = stream => {
        recordTimeCon = setInterval(() => {
          if (this.recordTime < 60) {
            this.recordTime++;
          } else {
            this.clickStopRecord();
          }
        }, 1000);
      // 创建一个用于通过JavaScript直接处理音频
        this.scriptProcessor = this.audioContext.createScriptProcessor(0, 1, 1)
        this.scriptProcessor.onaudioprocess = e => {
        // 去处理音频数据
          if (this.recordStatus === 'RECORDING') {
            this.audioData = transWorker.onmessage(e.inputBuffer.getChannelData(0))
          }
        }
      // 创建一个新的MediaStreamAudioSourceNode 对象，使来自MediaStream的音频可以被播放和操作
        this.mediaSource = this.audioContext.createMediaStreamSource(stream)
      // 连接
        this.mediaSource.connect(this.scriptProcessor)
        this.scriptProcessor.connect(this.audioContext.destination)
        this.connectWebSocket()
      }

      let getMediaFail = (e) => {
        this.$showCjToast({
          text: "请求麦克风失败",
          type: "warn",
          time: 1500
        });
        this.audioContext && this.audioContext.close()
        this.audioContext = undefined
      // 关闭websocket
        if (this.webSocket && this.webSocket.readyState === 1) {
          this.webSocket.close()
        }
      }
    },
    //点击开始录音
    clickStartRecord() {
      if (this.recordStatus != "START" || this.hasRecord == 1) {
        return;
      }
      if (this.isQuestionEnd == 0) { //念完题目才能开始录音
        return;
      }
      this.hasRecord = 1;
      this.wordAnly = '';
      this.isReject = 0;
      this.score = '';
      // this.stopListenAudio();
      this.recordStatus = "RECORDING";
      this.recordTime = 0;
      clearInterval(recordTimeCon);
      let $this = this;
      if (this.recordFlag) {
        $this.recorderInit()
      } else {
        if (this.isWeiXin) {
          wxUtilJs.startRecord().then(res => {
            recordTimeCon = setInterval(() => {
              if ($this.recordTime < 60) {
                $this.recordTime++;
              } else {
                $this.clickStopRecord();
              }
            }, 1000);
          }, failRes => {
            this.$showCjToast({
              text: "开启录音失败,请确认是否授权录音",
              type: "warn",
              time: 1000
            });
            this.recordStatus = "START";
            this.hasRecord = 0;
          });

        //60s后自动停止录音
          wxUtilJs.onVoiceRecordEnd().then(localId => {
            currentLocalId = localId;
            this.clickSentRecord();
          });
        } else {
          record.recOpen(() => {
            record.recStart();
            recordTimeCon = setInterval(() => {
              if ($this.recordTime < 60) {
                $this.recordTime++;
              } else {
                $this.clickStopRecord();
              }
            }, 1000);
            record.recVoiceRecordEnd(res => {
              this.blob = res;
              this.clickSentRecord();
            });
          }, () => {
            this.recordStatus = "START";
            this.hasRecord = 0;
          }, 'wav');
        }
      }
    },

    //点击停止录音
    clickStopRecord() {
      if (this.recordStatus != "RECORDING") {
        return;
      }
      clearInterval(recordTimeCon);
      if (this.recordFlag) {
        this.setStatus("START");
        this.audioContext && this.audioContext.close()
      } else {
        if (this.isWeiXin) {
          wxUtilJs.stopRecord().then(localId => {
            currentLocalId = localId;
            if (this.recordTime >= 1) {
              this.setStatus("START");
              this.clickSentRecord();
            }
          });
        } else {
          record.recStop(res => {
            this.blob = res;
            if (this.recordTime >= 1) {
              this.clickSentRecord();
            }
          });
        }
      }
      if (this.recordTime < 1) {
        this.$showCjToast({
          text: "录音时间太短",
          type: "warn",
          time: 1000
        });
        this.setStatus("START");
        this.hasRecord = 0;
      }
    },
    // 修改录音评测状态
    setStatus(recordStatus) {
      this.recordStatus = recordStatus
    },
    // 连接websocket
    connectWebSocket() {
      utilJs.postMethod(
        global.apiurl + "speech/changeAudio",
        {},
        res => {
          let iseWS
          if ('WebSocket' in window) {
            iseWS = new WebSocket(res.xfUrl)
          }
          this.webSocket = iseWS
          this.setStatus('RECORDING')
          iseWS.onopen = e => {
            this.setStatus('RECORDING')
        // 重新开始录音
            setTimeout(() => {
              this.webSocketSend()
            }, 500)
          }
          iseWS.onmessage = e => {
            this.result(e.data)
          }
          iseWS.onerror = e => {
            this.recorderStop(1)
          }
          iseWS.onclose = e => {
            this.recorderStop()
          }
        })
    },
    // 向webSocket发送数据
    webSocketSend() {
      if (this.webSocket.readyState !== 1) {
        return
      }
      let audioData = this.audioData.splice(0, 1280)
      let host = window.location.host;
      let contant = encodeURIComponent(this.examinationList[this.playIndex].problem).replace(/%C2%A0/g, '%20').replace(/%E2%80%A9/g, '').replace(/%E2%80%8B/g, '').replace(/%E2%80%8E/g, '')
      this.examinationList[this.playIndex].problem = decodeURIComponent(contant)
      var params = {
        common: {
          app_id: host == "kptest.ckjr001.com" || host == "kptest2.ckjr001.com" ? '5ce4a5a3' : '5d0c50e5',
        },
        business: {
          category: 'read_sentence', // read_syllable/单字朗读，汉语专有 read_word/词语朗读  read_sentence/句子朗读 https://www.xfyun.cn/doc/Ise/IseAPI.html#%E6%8E%A5%E5%8F%A3%E8%B0%83%E7%94%A8%E6%B5%81%E7%A8%8B
          rstcd: 'utf8',
          //adult（成人群体，不设置群体参数时默认为成人）youth（中学群体）pupil（小学群体，中文句、篇题型设置此参数值会有accuracy_score得分的返回）
          // group: this.examinationList[this.playIndex].crowdType == 1 ? 'adult' : this.examinationList[this.playIndex].crowdType == 2 ? 'youth' : 'pupil',
          sub: 'ise',
          ent: this.examinationList[this.playIndex].speakType == 1 ? 'cn_vip' : 'en_vip',
          tte: 'utf-8',
          cmd: 'ssb',
          auf: 'audio/L16;rate=16000',
          aus: 1,
          aue: 'raw',
          rst: 'entirety',
          ise_unite: "1",
          extra_ability: 'multi_dimension',
          text: '\uFEFF' + this.examinationList[this.playIndex].problem
        },
        data: {
          status: 0,
          encoding: 'raw',
          data_type: 1,
          data: this.toBase64(audioData),
        },
      }
      if (this.speakType == 1) {
        params.business.group = this.examinationInfo.crowdType == 1 ? 'adult' : this.examinationInfo.crowdType == 2 ? 'youth' : 'pupil'
        params.business.check_type = this.examinationInfo.difficultType == 2 ? 'common' : this.examinationInfo.difficultType == 3 ? 'hard' : 'easy'
      }
      this.webSocket.send(JSON.stringify(params))
      this.handlerInterval = setInterval(() => {
      // websocket未连接
        if (this.webSocket.readyState !== 1) {
          this.audioData = []
          clearInterval(this.handlerInterval)
          return
        }
      // 最后一帧
        if (this.audioData.length === 0) {
          if (this.recordStatus == "START") {
            this.webSocket.send(
            JSON.stringify({
              business: {
                cmd: 'auw',
                aus: 4,
                aue: 'raw'
              },
              data: {
                status: 2,
                encoding: 'raw',
                data_type: 1,
                data: '',
              },
            })
          )
            this.audioData = []
            this.$loading.show({
              text: "计算分数中..."
            });
            clearInterval(this.handlerInterval)
          }
          return false
        }
        audioData = this.audioData.splice(0, 1280)
      // 中间帧
        this.webSocket.send(
        JSON.stringify({
          business: {
            cmd: 'auw',
            aus: 2,
            aue: 'raw'
          },
          data: {
            status: 1,
            encoding: 'raw',
            data_type: 1,
            data: this.toBase64(audioData),
          },
        })
      )
      }, 40)
    },
    // 对处理后的音频数据进行base64编码
    toBase64(buffer) {
      let binary = ''
      let bytes = new Uint8Array(buffer)
      let len = bytes.byteLength
      for (var i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i])
      }
      return window.btoa(binary)
    },
    result(resultData) {
    // 识别结束
      let jsonData = JSON.parse(resultData)
      if (jsonData.code !== 0) {
        this.isReject = 1
        this.hasRecord = 0;
        this.$loading.hide();
        if (this.isReject == 1) {
          this.$showCjToast({
            text: "请根据题目进行朗读" + jsonData.code,
            type: "warn",
            time: 1500
          });
        }
        this.recordStatus = "START";
        this.webSocket.close()
      } else {
        if (jsonData.data && jsonData.data.data) {
          let data = Base64.decode(jsonData.data.data)
          let grade = parser.parse(data, {
            attributeNamePrefix: '',
            ignoreAttributes: false
          })
          this.hasRecord = 0;
          this.isReject = 0
          record.uploadAudioFile(this.blob, this.qiniuInfo, sres => {
            this.recordStatus = "START";
            // https://qnoss.ckjr001.com/1609986768842_mp_voice_v8g4534.wav
            this.answeraudio = sres
            this.setResultText(grade)
            // this.getPoints(sres);
          }, () => {});
        }
        if (jsonData.code === 0 && jsonData.data.status === 2) {
          this.webSocket.close()
        }
      }
    },
    //点击重录
    clickRecordAgain() {
      this.recordStatus = "START";
    },
    //点击发送
    clickSentRecord() {
      this.$loading.show({
        text: "计算分数中..."
      });
      // this.stopListenAudio();
      // this.$emit("closeAudioRecordModal");
      if (this.isWeiXin) {
        wxUtilJs.uploadVoice({
          localId: currentLocalId
        }).then(serverId => {
          this.recordStatus = "START";
          this.getPoints(serverId);
        });
      } else {
        record.uploadAudioFile(this.blob, this.qiniuInfo, sres => {
          this.recordStatus = "START";
          this.getPoints(sres);
        }, () => {});
      }
    },

    //上传音频
    syncUploadAudio(serverId) {
      utilJs.postMethod(
        global.apiurl + "common/downWxMediaSpx",
        {
          content: serverId
        },
        res => {
          // mp3Url = res.mp3Url;
          this.getPoints(res.wavUrl);
        },
        failRes => {
          this.$loading.hide();
        }
      );
    },
    setResultText(grade) {
      let $this = this;
      $this.$loading.hide();
      const readSentence = grade.xml_result.read_sentence.rec_paper
      if ($this.examinationList[$this.playIndex].speakType == 1) {
        this.score = readSentence.read_sentence.total_score;
      } else {
        this.score = readSentence.read_chapter.total_score
      }
    },
    getPoints(serverId) {
      let $this = this;
      utilJs.postMethod(
        global.apiurl + "speech/speakPractice",
        {
          text: $this.examinationList[$this.playIndex].problem,
          speakType: $this.examinationList[$this.playIndex].speakType,
          content: serverId
        },
        res => {
          $this.score = res.score;
          $this.isReject = res.isReject;
          // mp3Url = res.mp3Url;
          $this.$loading.hide();
          if ($this.problemShowType == 3 && $this.speakType == 2 && res.wordAnalysis) {
            if (!Array.isArray(res.wordAnalysis)) {
              for (let i = 0; i < res.wordAnalysis.word.length; i++) {
                if (res.wordAnalysis.word[i].total_score) {
                  if (Number(res.wordAnalysis.word[i].total_score) >= 85) {
                    if (i != res.wordAnalysis.word.length - 1) {
                      $this.wordAnly = $this.wordAnly + "<span style='color:#71DB78'>" + res.wordAnalysis.word[i].content + '</span> ';
                    } else {
                      $this.wordAnly = $this.wordAnly + "<span style='color:#71DB78'>" + res.wordAnalysis.word[i].content + '</span>';
                    }
                  } else if (Number(res.wordAnalysis.word[i].total_score) >= 60) {
                    if (i != res.wordAnalysis.word.length - 1) {
                      $this.wordAnly = $this.wordAnly + "<span style='color:#666666'>" + res.wordAnalysis.word[i].content + '</span> ';
                    } else {
                      $this.wordAnly = $this.wordAnly + "<span style='color:#666666'>" + res.wordAnalysis.word[i].content + '</span>';
                    }
                  } else {
                    if (i != res.wordAnalysis.word.length - 1) {
                      $this.wordAnly = $this.wordAnly + "<span style='color:#FB816D'>" + res.wordAnalysis.word[i].content + '</span> ';
                    } else {
                      $this.wordAnly = $this.wordAnly + "<span style='color:#FB816D'>" + res.wordAnalysis.word[i].content + '</span>';
                    }
                  }
                }
              }
            } else {
              for (let i = 0; i < res.wordAnalysis.length; i++) {
                for (let j = 0; j < res.wordAnalysis[i].word.length; j++) {
                  if (res.wordAnalysis[i].word[j].total_score) {
                    if (Number(res.wordAnalysis[i].word[j].total_score) >= 85) {
                      if (j != res.wordAnalysis[i].word.length - 1) {
                        $this.wordAnly = $this.wordAnly + "<span style='color:#71DB78'>" + res.wordAnalysis[i].word[j].content + '</span> ';
                      } else {
                        $this.wordAnly = $this.wordAnly + "<span style='color:#71DB78'>" + res.wordAnalysis[i].word[j].content + '</span>';
                      }
                    } else if (Number(res.wordAnalysis[i].word[j].total_score) >= 60) {
                      if (j != res.wordAnalysis[i].word.length - 1) {
                        $this.wordAnly = $this.wordAnly + "<span style='color:#666666'>" + res.wordAnalysis[i].word[j].content + '</span> ';
                      } else {
                        $this.wordAnly = $this.wordAnly + "<span style='color:#666666'>" + res.wordAnalysis[i].word[j].content + '</span>';
                      }
                    } else {
                      if (j != res.wordAnalysis[i].word.length - 1) {
                        $this.wordAnly = $this.wordAnly + "<span style='color:#FB816D'>" + res.wordAnalysis[i].word[j].content + '</span> ';
                      } else {
                        $this.wordAnly = $this.wordAnly + "<span style='color:#FB816D'>" + res.wordAnalysis[i].word[j].content + '</span>';
                      }
                    }
                  }
                }
                $this.wordAnly = $this.wordAnly + '.';
              }
            }
          }
          //学习模式下可以测任意次，不直接跳转下一题
          $this.hasRecord = 0;
          if ($this.isReject == 1) {
            $this.$showCjToast({
              text: "请根据题目进行朗读",
              type: "warn",
              time: 1500
            });
          }
        },
        failRes => {
          $this.hasRecord = 0;
          $this.recordStatus = "START";
          $this.$loading.hide();
        }
      );
    },
    replay() {
      if (this.recordStatus != "RECORDING") {
        this.showLoudspeaker = true;
        this.toPlay();
      }
    },
    playRadio() {
      let audio = document.getElementById("audio");
      audio.src = '';
      if (this.examinationList[this.playIndex].audioProblem) {
        audio.src = this.examinationList[this.playIndex].audioProblem;
        if (this.isWeiXin) {
          try {
            document.addEventListener(
              "WeixinJSBridgeReady",
              function () {
                document.getElementById("audio").play();
              },
              false
            );
            WeixinJSBridge.invoke("getNetworkType", {}, function (e) {// eslint-disable-line
              // 在这里拿到 e.err_msg, 这里面就包含了所有的网络类型
              document.getElementById("audio").play();
              console.log("WeixinJSBridgeWeixinJSBridgeWeixinJSBridgeWeixinJSBridge");
            });
          } catch (error) {
            // continue regardless of error
          }
        } else {
          document.getElementById("audio").play();
        }
      }
    },
    playAudioEnd() {
      // this.playAudioIndex ++;
      if (this.playAudioIndex == -1) {
        this.showLoudspeaker = false;
      }
      // if (this.type == 6) {
      this.isQuestionEnd = 1;
      // }
    },
    playAudioError() {

    },
    getQuestion() {
      let $this = this;
      this.examinationInfo = null;
      this.opList = [];
      this.rightAnswer = '';
      this.userAnSwer = [];
      this.problemShowType = -1;
      this.answerShowType = -1;
      this.playAudioIndex = -1;
      this.hasChoosed = 0;
      this.hasRecord = 0;
      this.isQuestionEnd = 0;
      this.showLoudspeaker = false;
      this.score = '';
      this.wordAnly = '';
      this.isReject = 0;
      this.praticeTimes = 0;

      if (this.recordStatus == "RECORDING") {
        if (this.isWeiXin) {
          wxUtilJs.stopRecord();
        } else {
          record != null && record.recClose();
        }
        clearInterval(recordTimeCon);
        this.recordStatus = "START";
      }
      if (!document.getElementById('audio').ended) {
        document.getElementById("audio").pause();
      }

      utilJs.getMethod(global.apiurl + 'exam/examProcess/' + this.paperMainId + '?topicId=0', function (res) {
        $this.examinationInfo = res;
        $this.rightAnswer = res.answer;
        $this.problemShowType = res.problemShowType;
        $this.paperDetailId = res.paperDetailId;
        $this.examId = res.examId;
        $this.speakType = res.speakType;
        $this.type = res.type;
        $this.loudspeaker = true;
        $this.examModel = res.paperInfo.examModel;
        $this.paperType = res.paperType;
        if ($this.type == 6 && $this.showIllustration) {
          // if ($this.$refs.illustrationBar.classList.indexOf('illustrationHide') > -1) {
          setTimeout(function () {
            $this.$refs.illustrationBar.classList.add('illustrationHide');
            setTimeout(function () {
              $this.showIllustration = false;
            }, 500)
          }, 5000);
          // }
        }
        $this.$nextTick(() => {
          setTimeout(function () {
            $this.playRadio();
          }, 1000)
        });
      });
    },
    pauseExam() { //暂停
      wxUtilJs.stopRecord()
      clearInterval(recordTimeCon);
      this.recordStatus = "START";

      if (!document.getElementById('audio').ended) {
        document.getElementById("audio").pause();
      }
      this.showPause = true;
    },
    timeToStr(timeSecond) {
      //将秒转化为00:00:00格式
      let hour =
        Math.floor(timeSecond / 3600) >= 10
          ? Math.floor(timeSecond / 3600)
          : "0" + Math.floor(timeSecond / 3600);
      let minute =
        Math.floor((timeSecond % 3600) / 60) >= 10
          ? Math.floor((timeSecond % 3600) / 60)
          : "0" + Math.floor((timeSecond % 3600) / 60);
      let second =
        Math.floor(timeSecond % 60) >= 10
          ? Math.floor(timeSecond % 60)
          : "0" + Math.floor(timeSecond % 60);
      return hour + ":" + minute + ":" + second;
    },
    // 记录播放进度
    setProgress: function () {
      let data = {
        ttId: this.ttId, //营期ID
        tpId: this.tpId, //环节ID
        tlId: this.tlId, //课时ID
        ratio: this.progress, //完成进度0-100
      }
      utilJs.postMethod(`${global.apiurl}k12/trainings/progress`, data, res => {
      });
    },
    //分享
    wechatShare: function () {
      let title = '';//this.examinationInfo.name;
      let shareImg = '';//this.examinationInfo.avatar ? this.examinationInfo.avatar : require('../../../assets/examination_defult.png');
      let shareUrl = '';//window.location.href.split("#")[0] + '#/homePage/examination/examinationDetail?ExaminationNo=' + this.topicId + '&refereeId=' + localStorage.getItem("userId");
      let shareDesc = '';//this.examinationInfo.shareDesc;//"共包含"+this.examinationInfo.hasPaper+"套考卷";
      utilJs.wechatConfig(shareUrl, title, shareImg, shareDesc, function () { }, true);
    },
    //手机端分享
    appShare: function () {
      var title = this.examinationInfo.name;
      var shareImg = this.examinationInfo.avatar ? this.examinationInfo.avatar : require('../../../assets/examination_defult.png');
      var shareUrl = window.location.href.split("#")[0] + '#/homePage/examination/examinationDetail?ExaminationNo=' + this.topicId + '&refereeId=' + localStorage.getItem("userId");
      var shareDesc = this.examinationInfo.shareDesc;
      utilJs.appShareTrue(title, shareImg, shareUrl, shareDesc);
    }
  },
  beforeRouteLeave(to, from, next) {
    clearInterval(recordTimeCon);
    clearInterval(timeCountDown);
    next();
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style scoped>
.option-bg {
  background:rgba(242,242,242,1);
}
.in {
  animation: zoomIn 0.3s ease-in-out;
  -webkit-animation: zoomIn 0.3s ease-in-out;
}
.stripe-right {
  color: #fff;
  background:rgba(113,219,120,1);
}
.stripe-wrong {
  color: #fff;
  background:rgba(251,129,109,1);
}
.test-bg {
  background-color: #7390FE
}
.pause-bg {
  z-index: 888;
  background-color: rgba(0, 0, 0, 0.4);
}
.record-circle {
  width:2.8rem;
  height:2.8rem;
  border-radius: 50%;
  background-color: rgba(115,144,254,1);
  box-shadow:0px 0px 0px 0.2rem rgba(115,144,254,0.3);
  -webkit-box-shadow:0px 0px 0px 0.2rem rgba(115,144,254,0.3);
}
.box{
  /* 最外层的盒子 */
  width:2.8rem;
  height:2.8rem;
  margin: 0 auto;
  position: relative;
  overflow: hidden;
  border-radius: 50%;
  background-color: rgba(115,144,254,1);
}
.mask{
  /* 遮住div多余的部分，呈现出线条的效果 */
  position: absolute;
  top: 0.15rem;
  left: 0.15rem;
  right: 0.15rem;
  bottom: 0.15rem;
  z-index: 2;
  border-radius: 50%;
  background-color: rgba(115,144,254,1);
}
.colorB {
  color: #FB816D;
}
.top-bx {
  box-shadow:0px 3px 20px 0px rgba(0, 0, 0, 0.05);
}
.record_bg {
  -webkit-animation: record_bg_change 2s infinite linear;
  animation: record_bg_change 2s infinite linear;
  animation-direction:alternate;
  -webkit-animation-direction:alternate;
}
.record_out {
  -webkit-transform: translate3d(0, 0, 0);
  -moz-transform: translate3d(0, 0, 0);
  -ms-transform: translate3d(0, 0, 0);
  -o-transform: translate3d(0, 0, 0);
  transform: translate3d(0, 0, 0);
  -webkit-animation: record_out_zoom 1s infinite linear;
  animation: record_out_zoom 1s infinite linear;
  animation-direction:alternate;
  -webkit-animation-direction:alternate;
}
.bg-fa {
  background-color: #fafafa;
}
.btn-wrap {
  border-top: 1px solid #ddd;
  background: #fff;
  height: 4rem;
}
.tr-bg {
  background: rgba(115,144,254,1);
}
.tr-bd {
  border: 1px solid #7390FE;
}
.tr-fc {
  color: #7390FE;
}
.tr-cd {
  background: rgba(115,144,254,0.5);
}
@-webkit-keyframes record_out_zoom{
    0%{
        box-shadow:0px 0px 0px 0.2rem rgba(115,144,254,0.3);
        -webkit-box-shadow:0px 0px 0px 0.2rem rgba(115,144,254,0.3);
    }
    100%{
        box-shadow:0px 0px 0px 0.5rem rgba(115,144,254,0.3);
        -webkit-box-shadow:0px 0px 0px 0.5rem rgba(115,144,254,0.3);
    }
}
@keyframes record_out_zoom{
    0%{
        box-shadow:0px 0px 0px 0.2rem rgba(115,144,254,0.3);
        -webkit-box-shadow:0px 0px 0px 0.2rem rgba(115,144,254,0.3);
    }
    100%{
        box-shadow:0px 0px 0px 0.5rem rgba(115,144,254,0.3);
        -webkit-box-shadow:0px 0px 0px 0.5rem rgba(115,144,254,0.3);
    }
}
@-webkit-keyframes record_bg_change{
    0%{
        opacity: 1;
    }
    100%{
        opacity: 0.6;
    }
}
@keyframes record_bg_change{
    0%{
        opacity: 1;
    }
    100%{
        opacity: 0.6;
    }
}
@keyframes zoomIn {
  0% {
    font-size: 0.3rem;
    width: 0.3rem;
    height: 0.3rem;
  }
  100% {
    font-size: 0.9rem;
    width: 2.5rem;
    height: 2.5rem;
  }
}
@-webkit-keyframes zoomIn {
  0% {
    font-size: 0.3rem;
    width: 0.3rem;
    height: 0.3rem;
  }
  100% {
    font-size: 0.9rem;
    width: 2.5rem;
    height: 2.5rem;
  }
}
</style>